package cn.liip.dao;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import cn.liip.beans.Student;
import cn.liip.util.MongoDBUtil;

public class ManageDaoMongoImpl implements IManageDao {
	MongoDBUtil mongoDBUtil = new MongoDBUtil();

	DBObject dbObject;

	// 取所有名单
	@Override
	public List getAllStudent() {
		List<Object> studentList = new ArrayList<Object>();
		try {
			studentList = mongoDBUtil.findAll(dbObject, "student", new Student().getClass().getName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return studentList;
	}
	// 添加学生

	@Override
	public void add(Student student) {
		dbObject = new BasicDBObject();
		dbObject.put("address", student.getAddress());
		dbObject.put("age", student.getAge());
		dbObject.put("name", student.getName());
		dbObject.put("number", student.getNumber());
		dbObject.put("sex", student.getSex());
		try {
			mongoDBUtil.add(dbObject, "student");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 查找学生信息

	@Override
	public Student findOne(String _id) {
		Student student = new Student();
		dbObject = new BasicDBObject();
		try {
			dbObject.put("_id", new ObjectId(_id));
			student = (Student) mongoDBUtil.findOne(dbObject, "student", new Student().getClass().getName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return student;

	}

	// 删除学生
	@Override
	public int del(String _id) {
		int result = -1;
		dbObject = new BasicDBObject();
		dbObject.put("_id", new ObjectId(_id));
		try {
			result = mongoDBUtil.remove(dbObject, "student");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	// 更新学生信息
	@Override
	public int update(Student student) {
		int result = -1;
		BasicDBObject value = new BasicDBObject();// 要修改的值都放在value中
		DBObject where = new BasicDBObject();// 查询条件 比方说 _id
		dbObject = new BasicDBObject();

		where.put("_id", new ObjectId(student.get_id()));

		value.put("address", student.getAddress());
		value.put("age", student.getAge());
		value.put("name", student.getName());
		value.put("number", student.getNumber());
		value.put("sex", student.getSex());
		dbObject.put("$set", value);
		try {
			result = mongoDBUtil.update(dbObject, where, "student");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}
